<template>
  <div class="activity-content">
    <template v-for="(item, index) in productList">
    <!-- <div :to="{name: 'productDetail', params: {commodityID: item.goodsId}, query: {keyword: keyword}}" class="activity-item" :class="{'activity-item__small':itemSize}"> -->
    <div :class="{'activity-item__small':itemSize, 'activity-item': true}">
      <span class="discount-card" v-if="item.personalLimited">人均限购{{item.personalLimitNum}}件</span>
      <span class="discount-card" v-else>特价</span>
      <div class="sell-out" v-if="item.stock < 1">
        <img class="sell-out-img" src="../../images/sellnull.png" />
      </div>
      <div class="sell-out" v-else-if="item.personalLimited && item.lastPersonalLimitNum === 0">
        <img class="sell-out-img" src="../../images/selllimit.png" />
      </div>
      <div class="pointer" @click="openDetail(item)">
        <div class="preview-img">
          <img class="img" :src="prefixImg + item.image" v-if="item.image"/>
          <img class="img" :src="loadImg" v-else/>
        </div>
        <div class="pro-info txt-center">
          <h3 class="pro-name ellipsis">{{item.goodsName}} {{item.brandName}}</h3>
          <h4 class="pro-type">{{item.standard}}</h4>
        </div>
      </div>
      <div class="price-box">
        <div class="price">
          <template v-if="isExamComputed === 1">
            <span class="now">￥{{item.pmtPrice | floatPrices}}</span>
            <span class="old">￥{{item.price | floatPrices}}</span>
            <span class="left">剩{{item.stock > 0 ? item.stock : 0}}件</span>
          </template>
          <p class="txt-center ft-14" v-else-if="isExamComputed === 4">登录后查看价格</p>
          <p class="txt-center ft-14" v-else>审核通过可查看</p>
        </div>
          <el-input-number class="input-num-self" :title="`包装数${item.packingNum}`"
            size="mini"
            @keydown.110.native.prevent=''
            v-model="numList[index]"
            :min="0"
            :max="item.stockLimit ? (item.personalLimited ? item.lastPersonalLimitNum : item.stock) : 99999"
            :step="item.packingNum"
            :ref="`pro_${index}`"
            @change="debounceChangeProNum($event, index, item.packingNum, item)" >
          </el-input-number>
        <button class="btn-buy"
        :disabled="disabledList[index]"
        :class="{'btn-disabled':disabledList[index]}"
        @click="timeAddShopcart(item.productId, index, item)"
        :ref="`buy_${index}`">添加</button>
      </div>
    </div>
    </template>
  </div>
</template>

<script>
import {prefixImg} from '@/tool/index'
import {InputNumber} from 'element-ui'
import { mapState, mapActions } from 'vuex'
import {changeProNumber} from '@/service/get-data'
import {eventBus} from '@/tool/events-bus'
import _ from 'lodash'

export default {
  name: 'StepProduct',
  components: {
    elInputNumber: InputNumber
  },
  props: {
    productList: {
      type: Array || Object,
      default: []
    },
    itemSize: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      loadImg: require('../../images/newload.png'),
      purchaseNum: 0, // 购买的数量
      numList: [],
      disabledList: [],
      flag: true,
      changeflag: true
    }
  },
  computed: {
    prefixImg () {
      return prefixImg
    },
    isExamComputed () {
      return this.$store.getters.loginStatus
    },
    keyword () {
      return this.$route.query.keyword
    },
    proLen () {
      return this.productList && this.productList.length
    },
    ...mapState({
      limitArr: state => state.shopcart.limitArr,
      shopcartId: state => state.shopcart.shopCartId
    })
  },
  methods: {
    ...mapActions(['fetchCartList']),
    openDetail (item) {
      if (item.stock < 1) return
      this.$router.push({name: 'productDetail', params: {commodityID: item.goodsId}, query: {keyword: this.$route.query.keyword}})
    },
    changeNumber (value) {
      console.log(value)
      const vm = this
      console.log(`${vm.$refs['number']}`)
      if (value > 20) {
        this.$nextTick(() => {
          vm.$refs['number'].$refs.input.setCurrentValue(5)
        })
      }
    },
    debounceChangeProNum (value, skuIndex, step, objitem) {
      this.debouncePro(value, skuIndex, step, objitem)
    },
    handle () {
      this.debouncePro()
    },
    returnFn (value, skuIndex, step, objitem) {
      return this.changeProNum(value, skuIndex, step, objitem)
    },
    changeProNum (value, skuIndex, step, objitem) {
      console.log(value)
      let shopcatNum = 0
      let surplusNum // 去掉购物车数量的剩余可购买数量
       // 如果不存在id请求购物车
      if (!this.shopcartId) {
        this.fetchCartList()
        this.shopcartId = this.$store.state.shopcart.shopCartId
      }
      let lastNum = value % step
      let leftNum = lastNum === 0 ? value : value - lastNum + step
      console.log(value, leftNum)
      // 循环 购物车是否有限购的商品
      if (objitem.personalLimited && objitem.lastPersonalLimitNum > 0) {
        this.limitArr.map((limitItm, limitInd) => {
          if (objitem.productId === limitItm.pid) {
            shopcatNum = limitItm.num
          }
        })
        surplusNum = objitem.lastPersonalLimitNum - shopcatNum
        console.log(`剩余库存${surplusNum}`)
        // 购物存货和限购数量一样
        if (surplusNum === 0) {
          this.$nextTick(() => {
            this.numList[skuIndex] = 0
            // debugger
            // this.$refs[`pro_${skuIndex}`][0].$refs.setCurrentValue(0)
            console.log(this.$refs[`pro_${skuIndex}`][0])
            this.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
          })
          this.$message(`抱歉,此商品限购期间每人限购${objitem.personalLimitNum}件,已达此商品的添加上限`)
        } else if (surplusNum > 0 && leftNum === surplusNum) { // 数量和剩余的数量相等时
          this.$nextTick(() => {
            this.numList[skuIndex] = leftNum
            // this.$refs[`pro_${skuIndex}`][0].$refs.setCurrentValue(leftNum)
            this.$refs[`pro_${skuIndex}`][0].setCurrentValue(leftNum)
          })
          this.$message('您的选购数量已达上限,请添加到购物车')
        } else if (surplusNum > 0 && leftNum > surplusNum) { // 添加数量过大
          this.$message('您的选购数量已达上限')
          this.$nextTick(() => {
            // debugger
            this.numList[skuIndex] = surplusNum
            this.$refs[`pro_${skuIndex}`][0].setCurrentValue(surplusNum)
            // this.$refs[`pro_${skuIndex}`][0].$refs.input.setCurrentValue(surplusNum)
          })
        } else if (surplusNum > 0 && leftNum < surplusNum) { // 可正常加入购物车
          this.$nextTick(() => {
            this.numList[skuIndex] = leftNum
            this.$refs[`pro_${skuIndex}`][0].setCurrentValue(leftNum)
          })
        }
      } else if (!objitem.personalLimited) {
        if (leftNum > objitem.stock) {
          this.$message('您的选购数量已达库存数量')
          this.$refs[`pro_${skuIndex}`][0].setCurrentValue(objitem.stock)
        }
      }
    },
    // 添加到购物车
    async addShopcat (proId, skuIndex, objitem) {
      console.log(this)
      // this.disabledList[skuIndex] = true
      // this.$set(this.disabledList, skuIndex, true)
      console.log(666)
      // 添加到购物车
      let purchaseNum = this.numList[skuIndex]
      if (purchaseNum === 0) {
        return
      }
      let vm = this
      let surplusNum
      let shopcatNum
      if (!purchaseNum) {
        if (objitem.personalLimited && objitem.lastPersonalLimitNum > 0) {
          this.limitArr.map((limitItm, limitInd) => {
            if (objitem.productId === limitItm.pid) {
              shopcatNum = limitItm.num
            }
          })
          surplusNum = objitem.lastPersonalLimitNum - shopcatNum
          if (!surplusNum) {
            setTimeout(() => {
              this.numList[skuIndex] = 0
              vm.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
            }, 200)
            this.$message.error('抱歉,您抢购的商品已达购买上限')
          }
          return
        }
      }
      if (!purchaseNum) {
        setTimeout(() => {
          this.numList[skuIndex] = 0
          vm.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
        }, 200)
        this.$message.error('请选择购买数量')
        return
      }
      let res = await changeProNumber(this.shopcartId, proId, '', purchaseNum, 0)
      // _arr['productList'][skuIndex]['number'] = leftNum
      if (res.data.resultCode && res.data.resultCode === 2000) {
        eventBus.$emit('show:pop')
        this.numList[skuIndex] = 0
        this.$nextTick(() => {
          vm.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
        })
        this.fetchCartList() // 更新购物车列表
        // this.$message({message: '已经添加货品的数量到购物车'})
      } else {
        this.$message.error({
          message: res.data.resultMsg
        })
      }
    },
    timeAddShopcart (proId, skuIndex, objitem) {
      if (this.flag) {
        this.addShopcat(proId, skuIndex, objitem)
      }
      this.flag = false
      setTimeout(() => {
        this.flag = true
      }, 300)
    },
    initDisabledList () {
      let _arr = []
      if (this.productList && this.productList.length > 0) {
        this.productList.map((pro, proIdx) => {
          _arr[proIdx] = false
        })
      }
      this.disabledList = _arr
    },
    setClass (index) {
      let obj = {'btn-disabled': this.disabledList[index]}
      // obj[`qqface${key}`] = true
      console.log(obj)
      return obj
    }
  },
  created () {
  },
  mounted () {
    let arr = new Array(this.proLen).fill(0)
    this.numList = arr
    this.initDisabledList()
    // let disabled = new Array(this.proLen).fill(false)
    // this.disabledList = this.disabledList.concat(disabled)
    // console.log(this.disabledList)
    this.debouncePro = _.debounce(function (value, skuIndex, step, objitem) {
      // console.log(this.disabledList)
      if (value === 0) return
      let shopcatNum = 0
      let surplusNum // 去掉购物车数量的剩余可购买数量
      // 如果不存在id请求购物车
      if (!this.shopcartId) {
        this.fetchCartList()
        this.shopcartId = this.$store.state.shopcart.shopCartId
      }
      // 包装盒
      let lastNum = value % step
      let leftNum = lastNum === 0 ? value : value - lastNum + step
      console.log(value, leftNum)
      if (lastNum !== 0) {
        this.$message(`您当前选择的商品是${step}件一起采购哦`)
        this.$refs[`pro_${skuIndex}`][0].setCurrentValue(leftNum)
        return
      }
      // 是否超过库存
      if (leftNum > objitem.stock) {
        this.$message('您的选购数量已达库存数量')
        this.$set(this.disabledList, skuIndex, true)
        return
      }
      if (leftNum === objitem.stock) {
        this.$message(`商品库存数量${objitem.stock}`)
      }
      // 循环 购物车是否有限购的商品
      if (objitem.personalLimited && objitem.lastPersonalLimitNum > 0) {
        this.limitArr.map((limitItm, limitInd) => {
          if (objitem.productId === limitItm.pid) {
            shopcatNum = limitItm.num
          }
        })
        surplusNum = objitem.lastPersonalLimitNum - shopcatNum
        console.log(`剩余库存${surplusNum}`)
        // 购物存货和限购数量一样
        if (surplusNum === 0) {
          // this.$nextTick(() => {
          //   this.numList[skuIndex] = 0
          //   this.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
          // })
          // this.disabledList[skuIndex] = true
          console.log(this.disabledList[skuIndex])
          this.$message(`抱歉,此商品限购期间每人限购${objitem.personalLimitNum}件,已达此商品的添加上限`)
          this.$set(this.disabledList, skuIndex, true)
          return
        // 购买数量大于等于剩余的数量时
        } else if (surplusNum > 0 && leftNum > surplusNum) {
          // this.$nextTick(() => {
          //   this.numList[skuIndex] = surplusNum
          //   // this.$refs[`pro_${skuIndex}`][0].$refs.setCurrentValue(leftNum)
          //   this.$refs[`pro_${skuIndex}`][0].setCurrentValue(surplusNum)
          // })
          this.$message('您的选购数量已达上限')
          console.log(this.$refs[`buy_${skuIndex}`][0])
          this.$set(this.disabledList, skuIndex, true)
          return
        // 可正常加入购物车
        } else if (surplusNum > 0 && leftNum <= surplusNum) {
          this.$nextTick(() => {
            this.numList[skuIndex] = leftNum
            // this.$refs[`pro_${skuIndex}`][0].setCurrentValue(leftNum)
          })
          this.$set(this.disabledList, skuIndex, false)
          return
        }
      }
      this.$set(this.disabledList, skuIndex, false)
    }, 300, {leading: true, trailing: false})
  },
  beforeRouteEnter (to, from, next) {
    next()
  },
  watch: {
    productList (value) {
      let len = value && value.length
      let arr = new Array(len).fill(0)
      this.numList = arr
    }
  }
}
</script>

<style lang="scss" scoped>
  .activity-content{
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
    }
    .activity-item{
        position: relative;
        width: 232px;
        margin-bottom: 10px;
        padding: 0 20px 16px;
        font-size: 0;
        display: inline-block;
        background: #FFFFFF;
        border-radius: 2px;
        margin-right: 10px;
        -webkit-transition: all 0.2s linear;
        transition: all 0.2s linear;
        overflow: hidden;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
      &:nth-child(5n){
        margin-right: 0;
      }
      .stock-num{
        display:inline-block;
        padding: 0 10px;
        line-height: 2;
        font-size: 14px;
        background: #413d3d;
        color: #ffffff;
      }
      .preview-img{
        height: 200px;
        width: 200px;
        margin: 0 auto 12px;
        .img{
          width: 100%;
          height: 100%;
          vertical-align: middle
        }
      }
      .pro-name{
        color: #666;
        font-size: 14px;
        line-height: 20px;
        margin-bottom: 4px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
      }
      .pro-type{
        color: #a3a3a3;
        font-size: 12px;
        line-height: 14px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
      }
      .price-box{
        margin-top: 12px;
        padding-bottom: 2px;
        // border-top: 1px solid rgba(220,220,220, .2);
        // padding-top: 16px;
      }
      .price{
        margin-bottom: 20px;
        font-size: 0;
      }
      .old{
        color: #bdbdbd;
        font-size: 12px;
        text-decoration: line-through;
      }
      .now{
        display: inline-block;
        font-size: 16px;
        padding-right:3px;
        color: #ff0f34;
        // font-weight: 550;
      }
      .old{
        color: #bdbdbd;
        font-size: 12px;
        text-decoration: line-through;
      }
      .left{
        float: right;
        color: #5c5c5c;
        font-size: 14px;
        margin-top: 2px;
      }
      .btn-buy{
        // display: inline-block;
        text-align: center;
        color: #FF0000;
        border-radius: 2px;
        font-size: 14px;
        line-height: 25px;
        border: 1px solid #FF0000;
        background: #fff;
        margin-bottom: 2px;
        width: 86px;
        float: right;
        cursor: pointer;
      }
      .btn-disabled{
        color: #999;
        border: 1px solid #ddd;
        background: #f0f0f0;
        cursor: not-allowed;
      }
      .cannot-buy{
        display:block;
        // width: 100%;
        // height:40px;
        text-align: center;
        color: #ffffff;
        background: #dfdfdf;
        // border-radius: 2px;
        // font-size: 16px;
        // line-height: 40px;
      }
      .sell-out{
        position:absolute;
        left:0;
        top:0;
        bottom: 0;
        right: 0;
        background: rgba(0,0,0,.63);
        z-index: 88;
        .sell-out-img{
          left: 50%;
          transform: translateX(-50%);
          position: absolute;
          top: 76px;
        }
      }
    }
    .activity-item__small{
      width: 220px;
      border: 1px solid #ececec;
      &:nth-child(4n) {
         margin-right: 0;
      }
      &:nth-child(5n){
        margin-right: 10px;
      }
    }
    .btn-yellow-over{
      display: inline-block;
      width:130px;
      height:40px;
      font-size:14px;
      color:rgba(51,51,51,1);
      text-align: center;
      line-height: 40px;
      background:rgba(251,205,59,1);
      border-radius:6px;
    }
    .pro-over-pos{
      position: absolute;
      bottom: 36px;
      left: 50%;
      margin-left: -65px;
      cursor: pointer;
    }
</style>
